<?php

namespace App\Http\Controllers\Saas;

use App\Http\Config\ErrorCode;
use App\Library\UploadFile;
use App\Models\Admin\Picture;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class UploadController extends BaseController
{
    // 图片上传方法
    public function uploadImage(Request $request)
    {
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        global $scf_data;
        if(!empty($scf_data["IS_SCF"])){
            if (!$request['file']){
                $this->returnData = ErrorCode::$admin_enum['params_error'];
                $this->returnData['msg'] = '缺少文件';
                return $this->return_result($this->returnData);
            }
            $type = ['image/jpg', 'image/png', 'image/jpeg', 'image/bmp'];
            $files = json_decode($request['file'],true);
            if (!in_array($files['type'], $type)){
                $this->returnData = ErrorCode::$admin_enum['params_error'];
                $this->returnData['msg'] = '文件类型错误';
                return $this->return_result($this->returnData);
            }
            $temp_file = tempnam(sys_get_temp_dir(),"php");  //临时文件
            file_put_contents($temp_file, base64_decode($files['content']));        //文件流写入文件
            $fileName = '/uploads/picture/'.date('Ymd')."/".md5(time()).".".pathinfo($files["name"], PATHINFO_EXTENSION);
            $pictureModel = new Picture();
            $url = $pictureModel->uploadImg($fileName, $temp_file);
            if (!$url){
                $this->returnData = ErrorCode::$admin_enum['params_error'];
                $this->returnData['msg'] = '上传图片失败';
                return $this->return_result($this->returnData);
            }
            $files['name'] = $fileName;
            $files["url"] = $url['ObjectURL'];
        }else{
            $base64_img = $request->file('file');
            $files = (new UploadFile([
                'upload_dir' => './uploads/picture/',
                'type'       => ['image/jpg', 'image/png', 'image/jpeg', 'image/bmp']
            ]))->upload($base64_img);
            if($files['code'] > 0) {
                return $this->return_result($files);
            }
        }
        DB::table('picture')->insertGetId([
            "name" => $files['name'], "uid" => $this->AU["id"], "type" => $files["type"], "status" => 1, "src" => $files["url"],
            "time" => Carbon::now(), "mall_id" => 0
        ]);
        $this->returnData['data'] = ['title' => $files['name'], "url" => $this->processingPictures($files['url']), "type" => $files['type'], "id" => $files["url"]];
        return $this->return_result($this->returnData);
    }

    public function getAll(Request $request)
    {
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        $page = $request['page'] ?: 1;
        $limit = $request['pageSize'] ?: 10;
        $start = ($page-1)*$limit;   //开始位置
        $rows = DB::table('picture')->where('uid',$this->AU["id"])->where(["mall_id" => 0])->where('status',1);
        $this->returnData['data'] = ["count" => $rows->count()];
        $this->returnData['data']['list'] = $rows->skip($start)->take($limit)->orderBy('id','desc')->get();
        $this->returnData['data']['list'] = json_decode(json_encode($this->returnData['data']['list']),true);
        foreach ($this->returnData['data']['list'] as &$v){
            $v['id'] = $this->processingPictures($v['name']);
            $v['url'] = $this->processingPictures($v['src']);
            $v['src'] = $this->processingPictures($v['src']);
        }
        return $this->return_result($this->returnData);
    }

    //软删除
    public function softDelete(Request $request)
    {
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(empty($request['ids'])){
            return $this->return_result(ErrorCode::code('params_not_exist', "ids"));
        }
//        $image_id = explode(",", $request['ids']);
        $res = DB::table('picture')->where('name',$request['ids'])->update(["status" => 0]);
        if (!$res){
            $this->returnData['code'] = 1;
            $this->returnData['msg'] = '删除失败';
        }
        return $this->return_result($this->returnData);
    }

    public function delete()
    {
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(empty($request['ids'])){
            return $this->return_result(ErrorCode::code('params_not_exist', "ids"));
        }
        $res = DB::table('picture')->where('name',$request['ids'])->delete();
        if (!$res){
            $this->returnData['code'] = 1;
            $this->returnData['msg'] = '删除失败';
        }
        return $this->return_result($this->returnData);
    }
}
